﻿using System;
using System.Threading;

namespace TSharpTest
{
    class temp
    {
        class Locker : IDisposable
        {
 
            private object synObj = null;
            private Locker(object obj) {
                if (Monitor.TryEnter(obj)) {
                    this.synObj = obj;
                }
                else {
                    throw new Exception("获取资源超时！");
                }
            }
            public static Locker Lock(object synObj) {
                return new Locker(synObj);
            }

            public void Dispose() {
                if (synObj != null) {
                    Monitor.Exit(synObj);
                }
            }
            public bool CanDo {
                get {
                    return this.synObj != null;
                }
            }
        }

        private static object syncRoot = new Object();
        public void Test() {
            //lock (syncRoot)
            //{
            //    Console.Write("I’m in!");
            //}
            using (var b = Locker.Lock(syncRoot))
                if (b.CanDo)
                    Console.WriteLine("I’m in!");
        }
    }
}